package com.jzx.provider.ucenter.user.service;

import com.google.common.collect.ImmutableMap;
import com.jzx.provider.common.constants.Expire;
import com.jzx.provider.common.constants.Mark;
import com.jzx.provider.common.constants.Status;
import com.jzx.provider.common.utils.CodeUtil;
import com.jzx.provider.common.utils.JwtUtil;
import com.jzx.provider.cv.service.CvService;
import com.jzx.provider.exception.MyErrorType;
import com.jzx.provider.exception.UcenterRuntimeException;
import com.jzx.provider.ucenter.user.dto.ChangePwdCommand;
import com.jzx.provider.ucenter.user.dto.LoginCommand;
import com.jzx.provider.ucenter.user.dto.UserCommand;
import com.jzx.provider.ucenter.user.model.User;
import com.jzx.provider.ucenter.user.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author daihuihui
 * @date 2019/2/7
 */
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CvService cvService;

    /**
     * 添加用户
     */
    public void save(UserCommand userCommand) {
        //验证手机验证码
    /*    boolean exits = stringRedisTemplate.hasKey(userCommand.getMobile() + "_" + userCommand.getCode());
        if (!exits) {
            throw new UcenterRuntimeException(MyErrorType.CODE_NOT_EXITS);
        }*/
        User user = User.builder().build();
        user.setStatus(Status.ENABLE.getValue());
        //密码加密
        user.setMobile(userCommand.getMobile());
        user.setSalt(CodeUtil.salt());
        user.setPassword(DigestUtils.md5DigestAsHex((user.getSalt() + userCommand.getPassword()).getBytes()));
        userRepository.save(user);
    }

    /**
     * 登录
     */
    public String login(LoginCommand loginCommand) {
        User user = userRepository.findOne(Example.of(User.builder()
                .mobile(loginCommand.getMobile())
                .build())).orElse(null);
        if (user == null) {
            throw new UcenterRuntimeException(MyErrorType.MOBILE_NOT_EXITS);
        }
        //用户被禁用
        if (user.getStatus().equals(Status.DISABLE.getValue())) {
            throw new UcenterRuntimeException(MyErrorType.USER_DISABLE);
        }
        if (!DigestUtils.md5DigestAsHex((user.getSalt() + loginCommand.getPassword()).getBytes()).equals(user.getPassword())) {
            throw new UcenterRuntimeException(MyErrorType.PASSWORD_ERROR);
        }
        //存入简历id
        List<Long> cvIdList = cvService.findCvIdByUserId(user.getId());
        String token = JwtUtil.genToken(ImmutableMap.of("id", user.getId() + "",
                "mobile", user.getMobile()));
        //stringRedisTemplate.opsForValue().set(token, StringUtils.join(cvIdList, Mark.CVIDS));
        //设置过期时间
        //stringRedisTemplate.expire(token, Expire.USER, TimeUnit.MINUTES);
        return token;
    }

    /**
     * 密码修改（忘记密码）
     */
    public void changePwd(ChangePwdCommand changePwdCommand) {
        User user = userRepository.findOne(Example.of(User.builder()
                .mobile(changePwdCommand.getMobile())
                .build())).orElse(null);
        if (user == null) {
            throw new UcenterRuntimeException(MyErrorType.MOBILE_NOT_EXITS);
        }
        //验证手机验证码
        boolean exits = stringRedisTemplate.hasKey(changePwdCommand.getMobile() + "_" + changePwdCommand.getCode());
        if (!exits) {
            throw new UcenterRuntimeException(MyErrorType.CODE_NOT_EXITS);
        }
        //修改密码
        String newPwd = DigestUtils.md5DigestAsHex((user.getSalt() + changePwdCommand.getPassword()).getBytes());
        user.setPassword(newPwd);
        userRepository.save(user);
    }

    /**
     * 给手机号发送验证码
     */
    public void sendCode(String mobile) {
        String code = CodeUtil.mobileCode();
        //通过aliyun短信服务发送

        //将code存入到redis
    /*    stringRedisTemplate.opsForValue().set(mobile + "_" + code, null);
        //设置过期时间
        stringRedisTemplate.expire(mobile + "_" + code, Expire.CODE, TimeUnit.MINUTES);*/
    }

    public Integer findUserIdBytoken(String token) {
        Map<String, String> map = null;
        try {
            map = JwtUtil.verifyToken(token);
        } catch (Exception e) {
            throw new UcenterRuntimeException(MyErrorType.USER_NOT_LOGIN);
        }
        return Integer.valueOf(map.get("id"));
    }
}
